﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace SharingCenter.Web.User.CurrentProfile
{
    using SharingCenter.Web.Classes;
    using System.Xml.Linq;
    using SharingCenter.Web.Classes.Profiles;

    public partial class Avatar : PageBase
    {
        Stream avatarStream;
        private static string tmpFileName;
        private readonly int resizedImageMaxSize = 600;

        protected void Page_Load(object sender, EventArgs e)
        {
            MessageBox1.Visible = Profile.Avatar.AvatarImageFileName == "";
            /*
            if (Profile.Avatar.AvatarImageFileName == "")
            {
                Image1.ImageUrl = WebConsts.AVATAR_DEFAULT_IMG_PATH;
            }
            else
            {
                Image1.ImageUrl = WebConsts.AVATAR_FOLDER + "/" + Profile.Avatar.AvatarImageFileName + "?" + DateTime.Now.Ticks;
            }
            */

            AsyncFileUpload1.UploadedComplete += new EventHandler<AjaxControlToolkit.AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedComplete);
            AsyncFileUpload1.UploadedFileError += new EventHandler<AjaxControlToolkit.AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedFileError);
            btnModifyAvatar.Click += new EventHandler(btnModifyAvatar_Click);
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        void btnModifyAvatar_Click(object sender, EventArgs e)
        {
           // save image selection
            char[] s = {':'};
            string[] selection = hdnSelection.Value.Split(s);
            tmpFileName = (string)Session["tmpAvatarImagePath"];

            using (System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(tmpFileName)))
            {
                Point startPoint = new Point(int.Parse(selection[0]), int.Parse(selection[1]));
                Point endPoint = new Point(int.Parse(selection[2]), int.Parse(selection[3]));
                Size clipSize = new Size(endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
                Rectangle rect = new Rectangle(startPoint, clipSize);

                using (System.Drawing.Image clippedImage = this.ClipImage(img, rect))
                {
                    ImageFormatConverter c = new ImageFormatConverter();
                    ImageFormat f = (ImageFormat)c.ConvertFromString(WebConsts.AVATAR_IMG_FORMAT);
                    string fileName = Profile.UserId + "." + WebConsts.AVATAR_IMG_FORMAT;
                    string thumbFileName = Profile.UserId + ".thumb." + WebConsts.AVATAR_IMG_FORMAT;
                    string tinyThumbFileName = Profile.UserId + ".tiny." + WebConsts.AVATAR_IMG_FORMAT;
                    string newName = WebConsts.AVATAR_FOLDER + "/" + fileName;
                    string thumbName = WebConsts.AVATAR_FOLDER + "/" + thumbFileName;
                    string tinyThumbName = WebConsts.AVATAR_FOLDER + "/" + tinyThumbFileName;

                    using (MemoryStream stream = new MemoryStream())
                    {
                        // Save image to stream.
                        clippedImage.Save(stream, ImageFormat.Jpeg);
                        ResizeFromStream(Server.MapPath(tinyThumbName), WebConsts.AVATAR_IMAGE_TINY_THUMB_SIZE.Height, stream);
                        ResizeFromStream(Server.MapPath(thumbName), WebConsts.AVATAR_IMAGE_THUMB_SIZE.Height, stream);
                        ResizeFromStream(Server.MapPath(newName), WebConsts.AVATAR_IMAGE_SIZE.Height, stream);
                    }

                    this.SetTopMostMessage("头像已更新。", true);

                    scDataContext cxt;
                    Sc_Profile myProfile = ProfileOperations.GetProfile(Profile.UserId, out cxt);

                    myProfile.AvatarImage = new XElement("Avatar",
                        new XElement("Normal", fileName),
                        new XElement("Thumbnail", thumbFileName),
                        new XElement("Tiny", tinyThumbFileName));
                    cxt.SubmitChanges();
                    cxt = null;
                }
            }
            
            //dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, Me.Sc_Profile);

            try
            {
                File.Delete(Server.MapPath((string)Session["tmpAvatarImagePath"]));
            }
            catch { }

            RefreshPage();
        }

        void AsyncFileUpload1_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            
        }

        void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (e.state == AjaxControlToolkit.AsyncFileUploadState.Success)
            {
                string ext =Path.GetExtension(e.filename);
                tmpFileName = WebConsts.AVATAR_TEMP_FOLDER + "/" + Profile.UserId + ext;
                avatarStream = AsyncFileUpload1.FileContent;
                Session["tmpAvatarImagePath"] = tmpFileName;
                this.ResizeFromStream(Server.MapPath(tmpFileName), resizedImageMaxSize, AsyncFileUpload1.FileContent);
            }
        }


        
    }
}
